package com.shreecon.lms.controller;

import static com.shreecon.lms.interfaces.IMessageConstant.CANNOT_BE_EMPTY;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shreecon.lms.common.EmployeeDetailsView;
import com.shreecon.lms.common.StringUtil;
import com.shreecon.lms.interfaces.LMSException;
import com.shreecon.lms.interfaces.manager.EmployeeManagerFactory;
 
/**
 * The Class LoginServlet.
 * 
 * @author Santhosh. Modified on Aug 13, 2011
 */
public class LoginServlet extends HttpServlet {
   
	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userName = (String)request.getParameter("username");
		String password = (String)request.getParameter("password");
		String target = "/pages/HomePage.jsp";
		System.out.println("Username :" + userName + " password :" + password);
		try {
        		validate(userName,password);
        		EmployeeDetailsView employeeDetailsView = EmployeeManagerFactory.getInstance().getEmployeeManager().getLoginDetail(userName.toUpperCase(), password);
        		request.setAttribute("employeeDetailsView", employeeDetailsView);
        		request.getSession().setAttribute("employeeDetailsView", employeeDetailsView);
		} catch (LMSException e) {
			System.out.println(e.getMessage());
			target = "/pages/index.jsp";
			request.setAttribute("error", e.getMessage());
			request.setAttribute("username", userName);
			System.out.println("setted");
		}
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(target);
		dispatcher.forward(request, response);
	}   
	
	/**
     * Validate.
     * 
     * @param userName
     *            the user name
     * @param password
     *            the password
     * @throws LMSException
     *             the lMS exception
     */
	private void validate(String userName,String password) throws LMSException{
		String userNameField = "UserName";
		String passwordField = "Password";
		StringUtil.checkForEmpty( userName, userNameField.concat( CANNOT_BE_EMPTY));
		StringUtil.checkForEmpty( password, passwordField.concat( CANNOT_BE_EMPTY));
	}
}